import { Button, Input } from "antd";
import TextArea from "antd/es/input/TextArea";
import React, { useState, useEffect, useRef } from "react";

import styles from "./index.module.scss";
import Message from "./components/Message";

const WebSocketChat = () => {
  const [messages, setMessages] = useState<any>([]);
  const [input, setInput] = useState("");
  const ws = useRef<any>(null);

  useEffect(() => {
    // 创建 WebSocket 连接
    ws.current = new WebSocket("ws://localhost:8089/chat");

    // 处理收到的消息
    ws.current.onopen = (event: any) => {
      console.log("WebSocket connection established");
    };

    // 处理收到的消息
    ws.current.onmessage = (event: any) => {
      console.log(event.data,'event.data')
      const messgaeDate = JSON.parse(event.data)
      setMessages((prevMessages: any) => [...prevMessages, messgaeDate]);
    };

    // 发生错误时触发
    ws.current.onerror = function (error: any) {
      console.error("WebSocket error:", error);
    };

    // 清理 WebSocket 连接
    return () => {
      ws.current.close();
    };
  }, []);

  const sendMessage = () => {
    if (ws.current && input) {
      ws.current.send(input);
      setInput("");
    }
  };

  return (
    <div>
      <h1>聊天室</h1>
      <div id="chat" className={styles.messageBlock}>
        {messages.map((message: any, index: number) => (
          <div key={index} className={styles.messageList}>
            <Message message={message?.message}></Message>
          </div>
        ))}
      </div>
      <div className={styles.sendPanle}>
        <TextArea
          id="message"
          placeholder="请输入发送的消息"
          value={input}
          onChange={(e) => setInput(e.target.value)}
        />
        <Button
          className={styles.chatSendButton}
          onClick={sendMessage}
          type="primary"
        >
          发送
        </Button>
      </div>
    </div>
  );
};

export default WebSocketChat;
